import Request from "luch-request"

import { getAccessToken, getActId } from '@/utils/auth'
import { baseURL } from "@/config";

const http = new Request();
/**

 * @description 修改全局默认配置

 * @param {Function}

 */
http.setConfig((config) => {
    /* config 为默认全局配置*/
    config.baseURL = baseURL; /* 根域名 */
    return config;
});
//请求前拦截

http.interceptors.request.use((config) => {
    /* cancel 为函数，如果调用会取消本次请求。需要注意：调用cancel,本次请求的catch仍会执行。必须return config */
    const token = getAccessToken()
    const actId = getActId()
    // console.log(token);
    config.header = {
        ...config.header,
        Authorization: token,
        actId: actId
    };
    return config;
});
//请求之后拦截

http.interceptors.response.use(
    (response) => {
        if (response.data.status == 401) {
            uni.showToast({
                title: "登录状态失效",
                icon: "none",
            });
            uni.redirectTo({
                url: "/pages/login/index",
            });
            return Promise.reject(response);
        }
        return response.data;
    },
    (response) => {
        if (response.data.status == 401) {
            uni.showToast({
                title: "登录状态失效",
                icon: "none",
            });
            uni.redirectTo({
                url: "/pages/login/index",
            });
            return Promise.reject(response);
        }
        uni.showToast({
            title: JSON.stringify(response.data),
            icon: "none",
        });

        return response.data;
    }
);

export function request(config: any) {
    let option: any = {
        method: "GET",
        url: "",
        data: {},
        params: {},
    };
    option = Object.assign(option, config);
    console.log(option);
    return http.request(option);
}